<template>
  <el-dialog
    v-model="visible"
    title="电表开户"
    width="400px"
    append-to-body
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="账户ID" prop="accountId">
        <el-input 
          v-model="form.accountId" 
          placeholder="请输入账户ID（选填）"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="初始金额" prop="money">
        <el-input-number 
          v-model="form.money"
          :min="0"
          :precision="2"
          :step="10"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="handleOk">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { openAccount } from '@/api/device/eleMeter'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  electricityMeterId: {
    type: [String, Number],
    required: true
  }
})

const emit = defineEmits(['update:visible', 'ok'])
const { proxy } = getCurrentInstance()

const visible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const loading = ref(false)
const formRef = ref()
const form = ref({
  money: 0,
  accountId: ''
})

const rules = {
  money: [
    { required: true, message: '请输入初始金额', trigger: 'blur' },
    { type: 'number', min: 0, message: '初始金额不能小于0', trigger: 'blur' }
  ]
}

function handleCancel() {
  visible.value = false
  form.value = {
    money: 0,
    accountId: ''
  }
}

function handleOk() {
  formRef.value.validate(valid => {
    if (valid) {
      loading.value = true
      openAccount(props.electricityMeterId, form.value.money, form.value.accountId)
        .then(res => {
          if(res.code === 200) {
            proxy.$modal.msgSuccess('开户成功')
            visible.value = false
            emit('ok')
            form.value = {
              money: 0,
              accountId: ''
            }
          }
        })
        .finally(() => {
          loading.value = false
        })
    }
  })
}
</script> 